package pers.jing.android.helper.page

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import pers.jing.android.helper.AndroidSdkTools
import pers.jing.android.helper.ANDROID_SDK_PATH
import pers.jing.android.helper.AppUtils
import pers.jing.android.helper.DeviceManager
import pers.jing.android.helper.db.Database
import pers.jing.android.helper.model.DeviceInfo

/**
 * 设备页面的ViewModel
 */
class DeviceListViewModel(val database: Database, val deviceManager: DeviceManager): ViewModel() {

    private val _adbExists = MutableStateFlow<Boolean>(false)
    val adbExists = _adbExists.asStateFlow()
    private var androidSdkPath: String? = null

    private val _isRefreshing = MutableStateFlow(false)
    val  isRefreshing = _isRefreshing.asStateFlow()

    init {
        checkSdkInstalled()
    }

    fun checkSdkInstalled() {
        viewModelScope.launch(Dispatchers.IO) {
            androidSdkPath = database.getConfig(ANDROID_SDK_PATH)
            if (androidSdkPath == null) {
                _adbExists.update {
                    false
                }
                return@launch
            }
            val exists = AndroidSdkTools.checkAdbExists(androidSdkPath!!)
            _adbExists.update {
                exists
            }
            if (exists) {
                deviceManager.loadDevices()
            }
        }
    }

    fun getStateFlowDevices(): StateFlow<List<DeviceInfo>> {
        return deviceManager.getStateFlowDevices()
    }

    fun loadDevices() {
        viewModelScope.launch(Dispatchers.IO) {
            _isRefreshing.update {
                true
            }
            deviceManager.loadDevices()
            _isRefreshing.update {
                false
            }
        }
    }
}